package com.example.mall_system.controller;

import com.example.mall_system.common.Result;
import com.example.mall_system.entity.Address;
import com.example.mall_system.service.OrdersService;
import com.example.mall_system.service.PaymentService;
import com.example.mall_system.mapper.AddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    
    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private AddressMapper addressMapper;

    @PostMapping
    public Result<?> createOrder(
            @RequestParam Long userId,
            @RequestParam Long addressId,
            @RequestBody List<Long> cartItemIds) {
        try {
            System.out.println("创建订单请求 - userId: " + userId + ", addressId: " + addressId + ", cartItemIds: " + cartItemIds);
            Result<?> result = ordersService.createOrder(userId, addressId, cartItemIds);
            System.out.println("创建订单结果: " + result);
            return result;
        } catch (Exception e) {
            System.err.println("创建订单异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error(500, "创建订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/{id}/pay")
    public Result<?> payOrder(
            @PathVariable Long id,
            @RequestParam Integer paymentMethod) {
        return paymentService.processPayment(id, paymentMethod);
    }

    @PostMapping("/{id}/cancel")
    public Result<?> cancelOrder(
            @PathVariable Long id,
            @RequestParam Long userId,
            @RequestParam Integer role,
            @RequestParam String cancelReason) {
        try {
            System.out.println("取消订单请求 - orderId: " + id + ", userId: " + userId + ", role: " + role + ", reason: " + cancelReason);
            Result<?> result = ordersService.cancelOrder(id, userId, role, cancelReason);
            System.out.println("取消订单结果: " + result);
            return result;
        } catch (Exception e) {
            System.err.println("取消订单异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error(500, "取消订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/{id}/ship")
    public Result<?> shipOrder(@PathVariable Long id) {
        return ordersService.shipOrder(id);
    }

    @PostMapping("/{id}/complete")
    public Result<?> completeOrder(
            @PathVariable Long id,
            @RequestParam Long userId,
            @RequestParam Integer role) {
        return ordersService.completeOrder(id, userId, role);
    }

    @GetMapping("/{id}")
    public Result<?> getOrderDetail(
            @PathVariable Long id,
            @RequestParam Long userId,
            @RequestParam Integer role) {
        return ordersService.getOrderById(id, userId, role);
    }

    @GetMapping
    public Result<?> getUserOrders(@RequestParam Long userId) {
        return ordersService.getUserOrders(userId);
    }

    @GetMapping("/status/{status}")
    public Result<?> getOrdersByStatus(
            @PathVariable Integer status,
            @RequestParam Long userId) {
        return ordersService.getOrdersByStatus(userId, status);
    }
    
    // 获取用户默认地址
    @GetMapping("/default-address")
    public Result<?> getDefaultAddress(@RequestParam Long userId) {
        Address defaultAddress = addressMapper.selectDefaultByUserId(userId);
        if (defaultAddress == null) {
            // 如果没有默认地址，返回第一个地址
            List<Address> addresses = addressMapper.selectByUserId(userId);
            if (!addresses.isEmpty()) {
                defaultAddress = addresses.get(0);
            }
        }
        return Result.success(defaultAddress);
    }

    // 验证支付结果
    @PostMapping("/{id}/verify-payment")
    public Result<?> verifyPayment(
            @PathVariable Long id,
            @RequestBody String paymentData) {
        return paymentService.verifyPayment(id, paymentData);
    }

    // 退款接口
    @PostMapping("/{id}/refund")
    public Result<?> refundOrder(
            @PathVariable Long id,
            @RequestParam String reason) {
        return paymentService.refundPayment(id, reason);
    }

    // 更新订单地址
    @PutMapping("/{id}/address")
    public Result<?> updateOrderAddress(
            @PathVariable Long id,
            @RequestParam Long addressId,
            @RequestParam Long userId,
            @RequestParam Integer role) {
        return ordersService.updateOrderAddress(id, addressId, userId, role);
    }

    // 验证支付验证码
    @PostMapping("/{id}/verify-payment-code")
    public Result<?> verifyPaymentCode(
            @PathVariable Long id,
            @RequestParam Integer paymentMethod,
            @RequestParam String verificationCode) {
        return paymentService.verifyPaymentCode(id, paymentMethod, verificationCode);
    }

    // 取消支付
    @PostMapping("/{id}/cancel-payment")
    public Result<?> cancelPayment(
            @PathVariable Long id,
            @RequestParam Integer paymentMethod,
            @RequestParam Long userId) {
        return paymentService.cancelPayment(id, paymentMethod);
    }
}